//
//  IPhoneAlarmViewController.m
//  IPhoneAlarm
//
//  Created by Jeffrey Palm on 5/28/09.
//  Copyright Jeffrey Palm 2009. All rights reserved.
//

#import "IPhoneAlarmViewController.h"
#import <AVFoundation/AVFoundation.h>


@interface IPhoneAlarmViewController (PrivateMethods)
- (void)startAlarm:(id)param;
- (void)playAlarm:(id)param;
@end

@implementation IPhoneAlarmViewController

@synthesize alarmLabel;

- (void) viewDidLoad {
	[super viewDidLoad];
	CFBundleRef mainBundle = CFBundleGetMainBundle ();	
	CFURLRef fileURL =	CFBundleCopyResourceURL(mainBundle,CFSTR("alarm"),CFSTR("wav"),NULL);
	AudioServicesCreateSystemSoundID(fileURL,&soundID);	
}

- (void) alarm {
	NSLog(@"Set off alarm!");
	[alarmLabel setText:@"ALARM"];
	[NSThread detachNewThreadSelector:@selector(playAlarm:) toTarget:self withObject:nil];		
	[NSTimer scheduledTimerWithTimeInterval:kAlarmSleep target:self selector:@selector(startAlarm:) userInfo:nil repeats:YES];
}

- (void)playAlarm:(id)param {
	NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init];
	NSLog(@"playAlarm");
	CFBundleRef mainBundle = CFBundleGetMainBundle ();	
	CFURLRef fileURL =	CFBundleCopyResourceURL(mainBundle,CFSTR("alarm"),CFSTR("wav"),NULL);	
	NSLog(@"Using URL %@", fileURL);
	while (TRUE) {		
		AudioServicesPlaySystemSound(soundID);
		[NSThread sleepForTimeInterval:4.5];
	}
	[autoreleasepool release];
}

- (void)startAlarm:(id)param {
	NSLog(@"startAlarm");
	UIColor *background;
	UIColor *foreground;
		NSLog(@"Changing color");
		if (greenBackground) {
			background = [UIColor greenColor];
			foreground = [UIColor redColor];
		} else {
			foreground = [UIColor greenColor];
			background = [UIColor redColor];			
		}
		[[self alarmLabel] setTextColor:foreground];
		[[self view] setBackgroundColor:background];
		greenBackground = !greenBackground;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
}


- (void)dealloc {
    [super dealloc];
}

@end
